/**
 * 配合node服务器端自动刷新的JS 需要在页面中引用，当文件发生改变页面会自动刷新。2017-12-07 Myweb
 * */
if ('WebSocket' in window) {
    (function () {
        function refreshCSS() {
            var sheets = [].slice.call(document.getElementsByTagName("link"));
            var head = document.getElementsByTagName("head")[0];
            for (var i = 0; i < sheets.length; ++i) {
                var elem = sheets[i];
                head.removeChild(elem);
                var rel = elem.rel;
                if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() ==
                    "stylesheet") {
                    var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
                    elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date()
                        .valueOf());
                }
                head.appendChild(elem);
            }
        }
        var socket = new WebSocket('ws://127.0.0.1:3001');
        socket.onmessage = function (msg) {
            if (msg.data == 'reload') window.location.reload();
            else if (msg.data == 'css') refreshCSS();
        };
        socket.onerror = function() {
            console.log('发生了错误，页面刷新可能不及时');
        };
        socket.onopen=function () {
            socket.send(document.title);
        };

        if (sessionStorage && !sessionStorage.getItem('FirstTime')) {
            console.log('实时刷新已激活.');
            sessionStorage.setItem('FirstTime', true);
        }
    })();
} else {
    console.error('浏览器版本过低，不支持websocket!');
}
